#!/usr/bin/env node

const http = require('http'),
      Koa = require('koa'),
      list = require('./data.js'),
      fs = require('fs'),
      log = console.log;

let arr = [];

function getPage(){
    let html = fs.readFileSync('./chapters.html').toString('utf8').replace('<head>',`<head><meta charset='utf-8'>`);
    return html;
}
  let dataList = list.chapterList;
function getData() {
  dataList.map((item)=>{
    let time =  new Date(item.publishTimer).getTime();
    arr.push(time);
  })

    function sortfn(a,b){
      return b-a;
    }
    arr.sort(sortfn);
  

 let j = 0;
 let obj = {};
  for(var i=0;i<arr.length;i++){
    if(new Date(dataList[i].publishTimer).getTime() == arr[j]){
      obj = dataList[j];
      dataList[j]=dataList[i];
      dataList[i]=obj;
      j++;
    }
  }
  console.log(dataList);

  return dataList;
}


http.createServer((req, res) => {

  if (req.url === '/') {
        res.end(getPage());
          
  } else if (req.url === '/getlist') {
        res.end(JSON.stringify(getData()));
          
  }else{
    if(req.url!==('/favicon.ico')){
      res.end(fs.readFileSync(`.${req.url}`));
    }else{
      return;
    }
                         
              
  }   

 

}).listen(8080);

